<?php
namespace App\Models;

use App\User;
use Illuminate\Database\Eloquent\Model;

class BookShelf extends Model{

    //指定表名
    protected $table= 'book_shelf';
    //指定主键
    protected $primaryKey= 'id';
    //允许批量赋值字段
    protected $fillable = ['book_id','user_id','status','last_read_chapter','index'];

    const SUCCESS_STATUS = 1;
    const ERROR_STATUS = 0;

    public $timestamps = true;

    //书架限制数量
    static $bookShelfLimit = 20;


    /**
     * 关联User表 多对一
     * 第一个参数：要关联的表对应的类
     * 第二个参数：中间表的表名
     * 第三个参数：当前表跟中间表对应的外键
     * 第四个参数：要关联的表跟中间表对应的外键
     */
    public function userBelongsTo()
    {
//        1、一对一使用方法：hasOne()
//        2、一对多使用方法：hasMany()
//        3、多对一使用方法：belongsTo()
//        4、多对多使用方法：belongsToMany()
        return $this->belongsTo('App\User','user_id','id');
    }

    /**
     * 获取指定用户书架列表
     * @param int $userId
     * @return int $count
     * */
    public static function getBookShelfList(int $userId)
    {
        $bookShelfList = User::find($userId)->bookShelfMethodMany()
            ->where('book_shelf.status',self::SUCCESS_STATUS)
            ->get(['books.id as book_id','book_shelf.id as book_shelf_id','name','image','is_over','type','writer','intro','click_num','new_chapter','chapter_count','last_read_chapter','index']);
        return $bookShelfList;
    }

    /**
     * 获取书架详情
     * @param int $userId
     * @param int $bookId
     * @return array $bookShelf
     * */
    public static function getBookShelfInfo(int $userId,int $bookId)
    {
        $bookShelf = BookShelf::where('user_id',$userId)
            ->where('book_id',$bookId)
            ->first();
        return $bookShelf;

    }

    /**
     * 获取指定用户下书架总数
     * @param int $userId
     * @return int $count
     * */
    public static function getBookShelfCount(int $userId)
    {
        $count = BookShelf::where('user_id',$userId)->where('status',self::SUCCESS_STATUS)->count();
        return $count;
    }

    /**
     * 判断小说是否加入书架
     * @param int $userId
     * @param int $bookId
     * @return int
     * */
    public static function isBookShelf(int $userId,int $bookId)
    {
        $bookShelf = self::getBookShelfInfo($userId,$bookId);
        if (empty($bookShelf)){
            return 0;
        }
        return 1;
    }

    /**
     * 根据小说ID获取加入书架的用户列表
     * @param int $bookId
     * @return array $userList
     * */
    public static function getUserListByBookId($bookId)
    {
        $userList = BookShelf::where('book_id',$bookId)
            ->where('status',self::SUCCESS_STATUS)
            ->with('userBelongsTo')
            ->get()
            ->toArray();
        $userList = array_column($userList,'user_belongs_to');
        return $userList;
    }
}
